package com.ruoyi.car.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.ruoyi.car.business.domain.BusBpmnInfo;
import com.ruoyi.car.business.domain.BusCarPackageAudit;
import com.ruoyi.car.business.domain.BusServiceItem;
import com.ruoyi.car.business.mapper.BusServiceItemMapper;
import com.ruoyi.car.business.query.ServiceItemQuery;
import com.ruoyi.car.business.service.IBusBpmnInfoService;
import com.ruoyi.car.business.service.IBusCarPackageAuditService;
import com.ruoyi.car.business.service.IBusServiceItemService;
import com.ruoyi.common.core.page.TablePageInfo;
import com.ruoyi.common.exception.business.BusinessException;
import com.ruoyi.common.utils.ShiroUtils;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 养修服务单项Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-01-24
 */
@Service
@Transactional
public class BusServiceItemServiceImpl implements IBusServiceItemService {
    @Autowired
    private BusServiceItemMapper serviceItemMapper;
    @Autowired
    private IBusCarPackageAuditService carPackageAuditService;
    @Autowired
    private IBusBpmnInfoService bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;

    @Override
    public TablePageInfo<BusServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BusServiceItem>(serviceItemMapper.selectForList(qo));
    }

    @Override
    public void save(BusServiceItem serviceItem) {
        // 前台传入的参数, 需谨慎处理 传入的对象不能直接进行数据库的操作
        BusServiceItem item = new BusServiceItem();
        item.setName(serviceItem.getName());
        item.setOriginalPrice(serviceItem.getOriginalPrice());
        item.setDiscountPrice(serviceItem.getDiscountPrice());
        item.setCarPackage(serviceItem.getCarPackage());
        item.setInfo(serviceItem.getInfo());
        item.setCreateTime(new Date());
        item.setServiceCatalog(serviceItem.getServiceCatalog());
        // 判断是否为套餐
        if (BusServiceItem.CARPACKAGE_YES.equals(item.getCarPackage())) {
            // 如果是套餐,审核状态设置成初始化
            item.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
        } else {
            //  如果不是套餐,审核状态设置无需审核
            item.setAuditStatus(BusServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        serviceItemMapper.insert(item);
    }

    @Override
    public BusServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(BusServiceItem serviceItem) {
        // 处于上架状态,审核中状态,不能进行修改 传入的对象不能直接进行数据库的操作
        BusServiceItem oldItem = this.get(serviceItem.getId());
        if (BusServiceItem.SALESTATUS_ON.equals(oldItem.getSaleStatus()) // 处于上架状态
                || BusServiceItem.AUDITSTATUS_AUDITING.equals(oldItem.getAuditStatus())) { // 处理审核中
            throw new BusinessException("非法操作");
        }
        // 如果是套餐,已经审核通过,想再进行修改,审核状态修改为初始化状态
        if (BusServiceItem.AUDITSTATUS_APPROVED.equals(oldItem.getAuditStatus())) {
            oldItem.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
        }
        // 把前台的属性设置在当前对象中
        oldItem.setName(serviceItem.getName());
        oldItem.setOriginalPrice(serviceItem.getOriginalPrice());
        oldItem.setDiscountPrice(serviceItem.getDiscountPrice());
        oldItem.setServiceCatalog(serviceItem.getServiceCatalog());
        oldItem.setInfo(serviceItem.getInfo());
        serviceItemMapper.updateByPrimaryKey(oldItem);
    }

    @Override
    public void deleteBatch(BusServiceItem serviceItem) {
        if (BusServiceItem.SALESTATUS_OFF.equals(serviceItem.getSaleStatus())) {
            System.out.println(serviceItem.getAuditStatus());
            serviceItemMapper.updateByIsDelete(serviceItem.getId());
        }
    }

    @Override
    public List<BusServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    public void saleOn(Long id) {
        // 校验
        BusServiceItem oldObj = this.get(id);
        if (oldObj != null) {
            // 当处于上架状态,不需要做事情
            if (BusServiceItem.SALESTATUS_ON.equals(oldObj.getSaleStatus())) {
                return;
            }
            // 如果是套餐且处于非审核通过,不允许进行上架操作
            if (BusServiceItem.CARPACKAGE_YES.equals(oldObj.getCarPackage())
                    && !BusServiceItem.AUDITSTATUS_APPROVED.equals(oldObj.getAuditStatus())) {
                throw new BusinessException("为未审核通过套餐不允许上架");
            }
            // 其他情况都可以进行上架操作
            serviceItemMapper.updateSaleStatus(id, BusServiceItem.SALESTATUS_ON);
        }
    }

    @Override
    public void saleOff(Long id) {
        serviceItemMapper.updateSaleStatus(id, BusServiceItem.SALESTATUS_OFF);
    }

    @Override
    public void changeStatus(Long serviceItemId, Integer auditstatus) {
        serviceItemMapper.changeAuditStatus(serviceItemId,auditstatus);
    }

    @Override
    @Transactional
    public void startAudit(Long id, Long bpmnInfoId, Long director, Long finance, String info) {
        BusServiceItem serviceItem = this.get(id);
        // 合理性校验
        // 是否套餐
        if(!BusServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())){
            throw new BusinessException("非法操作");
        }
        // 是否审核中或审核通过状态
        if(BusServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus()) ||
                BusServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())){
            throw new BusinessException("非法操作");
        }
        // 封装carPackageAudit对象
        BusCarPackageAudit audit = new BusCarPackageAudit();
        audit.setServiceItemId(serviceItem.getId());
        audit.setServiceItemName(serviceItem.getName());
        audit.setServiceItemInfo(serviceItem.getInfo());
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());
        audit.setBpmninfoId(bpmnInfoId);//BpmninfoId的id
        audit.setCreator(ShiroUtils.getUserId().toString());// 创建人
        audit.setInfo(info);
        audit.setCreateTime(new Date());
        carPackageAuditService.insertBusCarPackageAudit(audit);// 保持到数据库,回填id
        // 查询BpmnInfo
        BusBpmnInfo bpmnInfo = bpmnInfoService.selectBusBpmnInfoById(bpmnInfoId);
        // 获取流程定义的key
        String definitionKey = bpmnInfo.getActProcessKey();
        // 业务标识businessKey
        String businessKey = audit.getId().toString();
        // 存储流程变量
        Map<String, Object> params = new HashMap<>();
        params.put("director",director);
        if(finance!=null){
            params.put("finance",finance);
        }
        // 将Bigdecimal转成Long类型
        params.put("discountPrice",serviceItem.getDiscountPrice().longValue());
        // 启动流程获取到流程实例对象
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(definitionKey, businessKey, params);
        // 流程审核对象关联流程实例对象
        audit.setInstanceId(processInstance.getId());
        // 查询当前流程实例目前处于那个任务中
        Task currentTask = taskService.createTaskQuery()
                .processInstanceId(processInstance.getId())
                .singleResult();
        // 获取当前流程运行的节点,获取这个节点处理人
        audit.setAuditorId(Long.parseLong(currentTask.getAssignee()));
        carPackageAuditService.updateBusCarPackageAudit(audit);
        // 更新服务单项的状态
        serviceItemMapper.changeAuditStatus(serviceItem.getId(),BusServiceItem.AUDITSTATUS_AUDITING);
    }
}
